package com.jiangfeixiang.springbootmybatis.controller;

import com.jiangfeixiang.springbootmybatis.entity.User;
import com.jiangfeixiang.springbootmybatis.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * Created by jiangfeixiang on 2018/8/19
 */
@RestController
//@Controller
//@RequestMapping(value="/users")     // 通过这里配置使下面的映射都在/users下
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 查询所有用户
     * 处理"/users"的GET请求，用来获取用户列表
     *还可以通过@RequestParam从页面中传递参数来进行查询条件或者翻页信息的传递
     * @return
     */
    @RequestMapping(value = "/user",method = RequestMethod.GET)
    public List<User> getAllUser() {
        List<User> users=userService.getAllUser();
        return users;
    }

    /**
     * 添加用户
     * 处理"/users"的POST请求，用来创建User
     * @param user
     */
    @RequestMapping(value = "/user",method = RequestMethod.POST)
    public String addUser(@ModelAttribute User user) {
        Integer addUser = userService.addUser(user);
        return "success";
    }

    /**
     * 根据id查询
     * 处理"/users/{id}"的GET请求，用来获取url中id值的User信息
     * url中的id可通过@PathVariable绑定到函数的参数中
     * @param id
     * @return
     */
    @RequestMapping(value = "/user/{id}",method = RequestMethod.GET)
    public User getUserById(@PathVariable("id") Integer id) {
        User user=userService.getUserById(id);
        return user;
    }



    /**
     * 更新用户
     * 处理"/users/{id}"的PUT请求，用来更新User信息
     * @param user
     */
    @RequestMapping(value="/user/{id}",method = RequestMethod.PUT)
    public String updateUser(@PathVariable("id") Integer id, @ModelAttribute User user) {
        Integer updateUser = userService.updateUser(user);
        return "success";
    }

    /**
     * 处理"/users/{id}"的DELETE请求，用来删除User
     * @param id
     */
    @RequestMapping(value="/user/{id}",method = RequestMethod.DELETE)
    public String deleteUserById(@PathVariable("id") Integer id) {
        Integer deleteUserById = userService.deleteUserById(id);
        return "success";
    }
}
